<?php
// +----------------------------------------------------------------------
// | zlserver [ 小程序 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------
namespace app\job\import;

use think\exception\ErrorException;
use think\facade\Validate;
use think\queue\Job;
use app\common\model\BookInfo as BookInfoModel; 
use app\common\model\BookInfoImport as BookInfoImportModel;

use app\common\model\Ietask;
use think\facade\Log;

class BookInfo
{
    protected $rule = [
        'book_name' => 'require',
        'book_price' => 'require',
        'book_author' => 'require',
        'book_concern' => 'require',
        'book_isbn' => 'require|number',
        'book_edition' => 'require',
        'book_date' => 'require',
    ];
    
    protected $msg = [
        'book_name.require' => '教材名称必填',
        'book_price.require' => '单价必填',
        'book_author.require' => '主编必填',
        'book_concern.require' => '出版社必填',
        'book_isbn.require' => 'ISBN书号必填',
        'book_isbn.number' => 'ISBN书号非法',
        'book_edition.require' => '版次必填',
        'book_date.require' => '出版年限必填',
    ];

    // 数据校验
    public function check($fileId, $filePath)
    {
        $re = [
            'count' => 0,
            'code' => 0,
            'msg' => ''
        ];
 
        $bookInfoModel = new BookInfoModel();
        $data = [];
        $errorData = [];
        try {
            $resXls=import_excel($filePath);  

            if ($resXls['status']) {
                // 清理导入提示
                unset($resXls['data'][0]);
                // 取表头
                $header = $resXls['data'][1];
                unset($resXls['data'][1]);
                $title = $bookInfoModel->csvHeader();
                $fields = [];

                // 遍历表头
                $last_index = 0;
                foreach ($title as $key => $val) {
                    // 从导入的数据表中查找字段位置
                    $index = array_search($val['desc'], $header);
                    if ($index !== false) {
                        $fields[] = [
                            'index' => $index,
                            'value' => $val['id']
                        ];
                    }
                    $last_index = $index;
                }
 
                if(count($fields) != 8) { 
                    $re['msg']  = '文件格式错误！请先下载导入模板，按模板要求准备导入数据后再次导入！';
                    $re['code']  = -1;
                    return $re;
                } else {
                    // 数据填充
                    $iData = [];
                    if ($fields) {
                        $i = 0;
                        foreach ($resXls['data'] as $key => $val) {
                            foreach ($fields as $fkey => $fval) {
                                $iData[$i][$fval['value']] = $val[$fval['index']];
                                if(is_object($iData[$i][$fval['value']])) {
                                    $iData[$i][$fval['value']] = $iData[$i][$fval['value']]->__toString();
                                }
                            }
                            $i++;
                        }
                    }
    
                    // 增加描述字段
                    $fields[] = [
                        'index' => $last_index + 1,
                        'value' => 'desc'
                    ];
                    
                    $count = count($iData);
                    $errCount = 0;
      
                    //$tmp_name_arr = array(); 
                    $tmp_isbn_arr = array(); 
                    
                    //$nameList = $bookInfoModel->getBookNameList();
                    $isbnList = $bookInfoModel->getIsbnList();
                    // 数据预处理 
                    foreach ($iData as $key => $val) {
                        $errFind = false;
                        //校验数据
                        $validate = new \think\Validate($this->rule, $this->msg);
                        $validate->batch(true);

                        // 数据预处理
                        $time = time();
                        $bookinfo['book_name'] = trim($val['book_name']);
                        $bookinfo['book_price'] = trim($val['book_price']);
                        $bookinfo['book_author'] = trim($val['book_author']);
                        $bookinfo['book_concern'] = trim($val['book_concern']);
                        $bookinfo['book_isbn'] = trim($val['book_isbn']);
                        $bookinfo['book_edition'] = trim($val['book_edition']);
                        $bookinfo['book_date'] = trim($val['book_date']);
                        $bookinfo['book_reward'] = trim($val['book_reward']);

                        $bookinfo['desc'] = '';
                        $bookinfo['error'] = 0;
 
                        if (!$validate->check($bookinfo)) {
                            $bookinfo['error'] = 1;
                            $errCount = $errCount + 1;
                            $errFind = true;

                            $index = 0;
                            foreach ($validate->getError() as $errKey => $value) {
                                if($index == 0) {
                                    $bookinfo['desc']  = $bookinfo['desc'] . $value;
                                } else {
                                    $bookinfo['desc']  = $bookinfo['desc'] . ';' . $value;
                                }
                                $index++;
                            }  
                        }

                        //判断ISBN号是否为13位有效数字
                        if (!preg_match("/^\d{13}$/", $bookinfo['book_isbn'])) {
                            $bookinfo['error'] = 1;
                                if($errFind) {
                                    $bookinfo['desc'] = $bookinfo['desc'] . ';' . 'ISBN书号必须为13位的纯数字，请规范填写！'; 
                                } else {
                                    $errCount = $errCount + 1;
                                    $errFind = true;
                                    $bookinfo['desc'] = $bookinfo['desc'] . 'ISBN书号必须为13位的纯数字，请规范填写！'; 
                                }
                        }
   
                        // 判断教材名称是否存在
                        // if (in_array($bookinfo['book_name'], $nameList)) {
                        //     $bookinfo['error'] = 1;
 
                        //     if($errFind) {
                        //         $bookinfo['desc'] =  $bookinfo['desc'] . ';' . $bookinfo['book_name'] . '教材名称已存在';
                        //     } else {
                        //         $errCount = $errCount + 1;
                        //         $errFind = true;
                        //         $bookinfo['desc'] =  $bookinfo['book_name'] . '教材名称已存在';
                        //     } 
                        // }
                        
                        // 判断ISBN是否存在
                        if (in_array($bookinfo['book_isbn'], $isbnList)) {
                            $bookinfo['error'] = 1;
 
                            if($errFind) {
                                $bookinfo['desc'] =  $bookinfo['desc'] . ';' . $bookinfo['book_isbn'] . 'ISBN已存在';
                            } else {
                                $errCount = $errCount + 1;
                                $errFind = true;
                                $bookinfo['desc'] =  $bookinfo['book_isbn'] . 'ISBN已存在';
                            } 
                        }

                        // 金额检测
                        if (!preg_match("/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/", $bookinfo['book_price'])) {
                            $bookinfo['error'] = 1;
                            if(strpos($bookinfo['desc'], '单价') === false) { 
                                if($errFind) {
                                    $bookinfo['desc'] =  $bookinfo['desc'] . ';' . '请输入一个合法的单价';
                                } else {
                                    $errCount = $errCount + 1;
                                    $errFind = true;
                                    $bookinfo['desc'] =  $bookinfo['desc'] . '请输入一个合法的单价';
                                }
                            }
                        }

                        // $keyExist = $bookinfo['book_name'];
                        // // 自身检测 
                        // if (in_array($keyExist, $tmp_name_arr)) { //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                        //     $bookinfo['error'] = 1;
                        //     if($errFind) {
                        //         $bookinfo['desc'] = $bookinfo['desc'] . ';' . '导入数据中存在重复数据：'.$keyExist; 
                        //     } else {
                        //         $errCount = $errCount + 1;
                        //         $errFind = true;
                        //         $bookinfo['desc'] = $bookinfo['desc'] . '导入数据中存在重复数据：'.$keyExist; 
                        //     }
                        // } else {
                        //     if($keyExist != '') {
                        //         $tmp_name_arr[] = $keyExist;
                        //     }
                        // }

                        $keyExist = $bookinfo['book_isbn'];
                        // 自身检测 
                        if (in_array($keyExist, $tmp_isbn_arr)) { //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                            $bookinfo['error'] = 1;
                            if($errFind) {
                                $bookinfo['desc'] = $bookinfo['desc'] . ';' . '导入数据中存在重复数据：'.$keyExist; 
                            } else {
                                $errCount = $errCount + 1;
                                $errFind = true;
                                $bookinfo['desc'] = $bookinfo['desc'] . '导入数据中存在重复数据：'.$keyExist; 
                            }
                        } else {
                            if($keyExist != '') {
                                $tmp_isbn_arr[] = $keyExist;
                            }
                        }

                        if ($bookinfo['error'] == 1) {
                            $errorData[$errCount - 1] = $bookinfo;
                        }
    
                        $data[$key] = $bookinfo;
                        unset($bookinfo);
                    }
                } 
            } else {
                $re['msg']  = $resXls['msg'];
                $re['code']  = -1;
                return $re;
            }
        } catch (Exception $e) {
            $re['msg']  = $e->getMessage();
            $re['code']  = -1;
            return $re;
        }

        $re['count'] = $count;
        $re['errCount'] = $errCount;
        $re['data'] = json_encode($data);
        $re['fileId'] = $fileId;
        $re['filePath'] = $filePath;
        $re['errData'] = json_encode($errorData);
        return $re;
    }

    //执行导入任务
    public function exec(Job $job, $params)
    {
        $ietaskModle = new Ietask();
        $ietaskInfo = $ietaskModle->where(['id' => $params['task_id']])->find();

        $bookInfoModel = new BookInfoModel();
        $message = [];
        $count = 0;         // 记录总数
        $progress = 0;
        try {
            $file = json_decode($params['params'], true);
            $resXls = import_excel($file['file_path']); 
            $count = count($resXls['data'])-2;

            if ($resXls['status']) {
                // 清理导入提示
                unset($resXls['data'][0]);
                // 取表头
                $header = $resXls['data'][1];
                unset($resXls['data'][1]);
                $title = $bookInfoModel->csvHeader(); 
                 
                $fields = []; 
                foreach ($title as $key => $val) {
                    $index = array_search($val['desc'], $header);
                    if ($index >= 0) {
                        $fields[] = [
                            'index' => $index,
                            'value' => $val['id']
                        ];
                    }
                }

                // 提取所有教材信息
                $iData = [];
                if ($fields) {
                    $i = 0;
                    foreach ($resXls['data'] as $key => $val) {
                        foreach ($fields as $fkey => $fval) {
                            $iData[$i][$fval['value']] = $val[$fval['index']];
                            if(is_object($iData[$i][$fval['value']])) {
                                $iData[$i][$fval['value']] = $iData[$i][$fval['value']]->__toString();
                            }
                        }
                        $i++;
                    }
                }
   
                unset($bookinfo_comment);
                $bookinfo_comment = []; 
                foreach ($iData as $key => $val) {
                    $bookinfo_comment[] = [
                        'book_name'         => trim($val['book_name']),
                        'book_price'        => trim($val['book_price']),
                        'book_author'       => trim($val['book_author']),
                        'book_concern'      => trim($val['book_concern']),
                        'book_isbn'         => trim($val['book_isbn']),
                        'book_edition'      => trim($val['book_edition']),
                        'book_date'         => trim($val['book_date']),
                        'book_reward'       => trim($val['book_reward']),
                        'ctime'             => time(),
                        'utime'             => time()
                    ];
     
                    // 每隔100条数据更新一次数据处理进度
                    $progress++; 
                    if($progress %100==0) {
                        // 批量插入数据 
                        $bookInfoModel->insertAll($bookinfo_comment); 

                        // 清理环境
                        unset($bookinfo_comment);
                        $bookinfo_comment = [];
                    }
                }

                // 批量插入数据 
                $num = $bookInfoModel->insertAll($bookinfo_comment);      
 
                $uData['status'] = $ietaskModle::IMPORT_SUCCESS_STATUS;
                $uData['message'] = '导入成功';
                if ($message) {
                    $uData['message'] .= json_encode($message);
                }

                $uData['count'] = $count;
                $ietaskModle->update($uData, ['id' => $params['task_id']]);
            } else {
                $uData['status'] = $ietaskModle::IMPORT_FAIL_STATUS;
                $uData['message'] = $resXls['msg'];
                $uData['utime'] = time();
                $ietaskModle->update($uData, ['id' => $params['task_id']]);
            }
        } catch (Exception $e) {
            $message[] = $e->getMessage();
        }
        if ($job->attempts() > 3) {
            $uData['status'] = $ietaskModle::IMPORT_FAIL_STATUS;
            $uData['message'] = '导入执行失败';
            $uData['utime'] = time();
            $ietaskModle->update($uData, ['id' => $params['task_id']]);
            $job->delete();
        }
    }

    public function failed($data)
    {

        // ...任务达到最大重试次数后，失败了
    }
}
